from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtWidgets import QFileDialog
from Ui_dialog2 import Ui_Dialog2
from Ui_dialog3 import Ui_Dialog3
from PyQt5.QtCore import QBasicTimer
import json
import six
import packaging
import packaging.version
import packaging.specifiers
import packaging.requirements

tasta = { 
    "version": "0.1.0",
    "command": "gcc",
    "args": [],    # 编译命令参数
    "problemMatcher": {
        "owner": "c",
        "fileLocation": ["relative", "${workspaceRoot}"],
        "pattern": {
            "regexp": "^(.*):(\\d+):(\\d+):\\s+(warning|error):\\s+(.*)$",
            "file": 1,
            "line": 2,
            "severity": 4,
            "column": 3,
            "message": 5
        }
    }
}


launch = {
    "version": "0.2.0",
    "configurations": [
        {
            "name": "C++ Launch (GDB)",                 # 配置名称，将会在启动配置的下拉菜单中显示
            "type": "cppdbg",                           # 配置类型，这里只能为cppdbg
            "request": "launch",                        # 请求配置类型，可以为launch（启动）或attach（附加）
            "launchOptionType": "Local",                # 调试器启动类型，这里只能为Local
            "targetArchitecture": "x86",                # 生成目标架构，一般为x86或x64，可以为x86, arm, arm64, mips, x64, amd64, x86_64
            "program": "${file}.exe",                   # 将要进行调试的程序的路径
            "miDebuggerPath":"C:\\MinGW\\bin\\gdb.exe", # miDebugger的路径，注意这里要与MinGw的路径对应
            "args": ["blackkitty",  "1221", "# #"],     # 程序调试时传递给程序的命令行参数，一般设为空即可
            "stopAtEntry": 0,                           # 设为true时程序将暂停在程序入口处，一般设置为false
            "cwd": "${workspaceRoot}",                  # 调试程序时的工作目录，一般为${workspaceRoot}即代码所在目录
            "externalConsole": 1,                       # 调试时是否显示控制台窗口，一般设置为true显示控制台
            "preLaunchTask": "gcc"                      # 调试会话开始前执行的任务，一般为编译程序，c++为g++, c为gcc
        }
    ]
}

C_CPP = {
    "configurations": [
        {
            "name": "Win32",
            "includePath": [
                #"C:\\MinGW\\include",
                #"C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include",
                #"C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include\\c++",
                #"C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include\\c++\\mingw32",
                #"C:\\MinGW\\lib\\gcc\\mingw32\\6.3.0\\include\\c++\\backward"
            ],

            "defines": [
                "_DEBUG",
                "UNICODE",
                "_UNICODE"
            ],
            "windowsSdkVersion": "",
            "intelliSenseMode": "clang-x64"
        }
    ],
    "version": 4
}

lists = []

class PortMain(QMainWindow,  Ui_Dialog2):
    
    def __init__(self,  parent = None):
        super(PortMain,  self).__init__(parent)
        self.timer = QBasicTimer()
        self.step = 0
        self.bool_but = False #path默认为假
        self.setupUi(self)
        self.Butt_fun()
        self.progressBar.setValue(self.step)

        
        
    def Butt_fun(self):
        
        #按键信号绑定
        self.pushButton.clicked.connect(self.pushButton_fun)
        self.pushButton_2.clicked.connect(self.pushButton_path)
        self.pushButton_4.clicked.connect(self.pushButton_bool)
        #self.pushButton_3.clicked.connect()
        
    def pushButton_fun(self): #json文件生成函数
        #print(tasta["command"])
        #self.progressBar
        if(self.lineEdit_2.text() != ""):
            '''self.pushButton_datat()
            self.pushButton_datal()'''
            self.timer.start(3, self)
            self.progressBar.setValue(self.step)
            '''print(launch["configurations"][0]["name"])
            datat = open('tasks.json',  'w')
            datal = open('launch.json',  'w')
            datat.write(json.dumps(tasta))
            datal.write(json.dumps(launch))
            datat.close()
            datal.close()
            tasta["args"] = []
            self.lineEdit_2.setPlaceholderText("")
            self.step = 0
            self.timer.stop()'''
        else:
            self.lineEdit_2.setPlaceholderText("路径不可为空!")
        
    def pushButton_datat(self): # 编译命令参数生成函数
        tasta["command"]  = self.comboBox.currentText()
        bat = list(self.lineEdit.text().split(','))
 
        bit = len(bat)

        bit = bit + 4

        for i in range(bit):
            if i==0:
                tasta["args"].append("-g") 
            elif i==1:
                tasta["args"].append("${file}")
            elif i==(bit-2):
                tasta["args"].append("-o")
            elif i==(bit-1):
                tasta["args"].append("${file}.exe")
            else:
                if(self.lineEdit.text() != ""):
                    tasta["args"].append(bat[i-2])
        #print(tasta)

    def pushButton_datal(self): #配置参数
        print(type(C_CPP["configurations"][0]["includePath"]))
        for x in range(0,len(C_CPP["configurations"][0]["includePath"])):
            try:
                C_CPP["configurations"][0]["includePath"].pop()
            except:
                print("err-1")
        launch["configurations"][0]["preLaunchTask"]  = self.comboBox.currentText()
        if self.comboBox.currentText() == "gcc":
            tasta["problemMatcher"]["owner"] = "c"
        else:
            tasta["problemMatcher"]["owner"] = "cpp"
        launch["configurations"][0]["name"]  = self.comboBox_2.currentText()
        launch["configurations"][0]["miDebuggerPath"] = self.lineEdit_2.text()
        launch["configurations"][0]["targetArchitecture"] = self.comboBox_3.currentText()
        try:
            for x in lists:
                C_CPP["configurations"][0]["includePath"].append(x)
        except:
            print("err")
        #C_CPP["configurations"][1]["includePath"] = lists
        #print(launch)
        print(C_CPP)

    def pushButton_path(self): #MinGW路径选择
        data = ""
        download_path , txt = QFileDialog.getOpenFileName(self,  
                                    "选取文件",  
                                    "C:/",  
                                    "All Files (*);;Text Files (*.txt)")

        download_path = list(download_path.split('/'))

        for i in range(len(download_path)):
            if(i<len(download_path)-1):
                data = data + download_path[i] + "\\"
            else:
                data = data + download_path[i]
        self.lineEdit_2.setText(data)

    def pushButton_bool(self):
        """默认不生成c_cpp_properties.json"""
        if self.bool_but == False:
            self.bool_but = True
        else:
            self.bool_but = False

    def timerEvent(self, e):

        if self.step >= 100:
            self.pushButton_datat()
            self.pushButton_datal()
            self.timer.stop()
            datat = open('tasks.json',  'w')
            datal = open('launch.json',  'w')

            if self.bool_but == True: #path按钮为真时生成c_cpp
                data2 = open('c_cpp_properties.json', 'w')
                data2.write(json.dumps(C_CPP))
                data2.close()

            datat.write(json.dumps(tasta))
            datal.write(json.dumps(launch))
            datat.close()
            datal.close()
            tasta["args"] = []
            self.lineEdit_2.setPlaceholderText("")
            self.step = 0
            return
        self.step = self.step+1
        self.progressBar.setValue(self.step)
    
    def Port_show(self):#显示窗体
        self.show()

    def Port_close(self):#关闭窗体
        self.close()


class PortMain2(QMainWindow,  Ui_Dialog3):
    def __init__(self,  parent = None):
        super(PortMain2,  self).__init__(parent)
        self.setupUi(self)
        self.Butt_fun()

    def Butt_fun(self):
        self.pushButton_3.clicked.connect(self.pushButton_path)
        self.pushButton_4.clicked.connect(self.Reduction_path)
        #按键信号绑定
        #return

    def pushButton_path(self): #MinGW转到定义路径选择
        data = ""
        download_path = QFileDialog.getExistingDirectory(self,  
                                    "选取文件",  
                                    "C:/")
        try:
            download_path = list(download_path.split('/'))

            for i in range(len(download_path)):
                if(i<len(download_path)-1):
                    data = data + download_path[i] + "\\"
                else:
                    data = data + download_path[i]
            print(data)
            lists.append(data)
            self.listWidget.addItem(data)
            #self.removeItemWidget(self,QListWidgetItem) takeItem
        except:
            print("err")

    def Reduction_path(self): #删除一个
        try:
            #print(self.listWidget.count())
            lists.pop()
            #print(lists)
            self.listWidget.clear()
            for datas in lists:
                self.listWidget.addItem(datas)
            #self.listWidget.removeItemWidget(self.listWidget.count())
        except:
            print("err1")

    def Port_show2(self):#显示窗体2
        self.show()

    def Port_close2(self):#关闭窗体2
        self.close()
        
        
if __name__ == "__main__":
    import sys
    app = QApplication(sys.argv)
    ui = PortMain() #实例化对象
    ui2 = PortMain2()
    ui.show()
    ui.pushButton_3.clicked.connect(ui.Port_close)
    ui.pushButton_3.clicked.connect(ui2.Port_show2)
    ui2.pushButton.clicked.connect(ui2.Port_close2)
    ui2.pushButton.clicked.connect(ui.Port_show)
    #ui2.show()
    sys.exit(app.exec_())